/* 
 * PropertiesHelper.java 19.06.2011
 *  
 *  
 * Candidate: Alessandra Otterbach
 * Prometric ID: Algisina1
 * Username: Algisina
 *  
 * Sun Certified Developer for Java 2 Platform, Standard Edition Programming 
 * Assignment (CX-310-252A)
 *  
 * This class is part of the Programming Assignment of the Sun Certified 
 * Developer for Java 2 Platform, Standard Edition certification program, must 
 * not be used out of this context and must be used exclusively by Sun 
 * Microsystems, Inc. 
 */
package suncertify.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import suncertify.ps.GuiExceptionHandler;

/**
 * Helper class to read and write the start configuration properties to a
 * properties file. 
 * 
 * @author Alessandra Otterbach
 * 
 */
public class PropertiesHelper {

    public static final String PROP_PATH = "path";
    public static final String PROP_IP = "ip";
    public static final String PROP_PORT = "port";

    /**
     * Gets the properties out of the file suncertify.properties. File schema
     * is:
     * 
     * path=xxxxx <br>
     * ip=xxxxxx <br> 
     * port=xxxxxx
     * 
     */
    public static Properties readProperties() {
	Properties properties = new Properties();
	try {
	    File file = new File("suncertify.properties");
	    FileInputStream in = new FileInputStream(file);
	    properties.load(in);
	} catch (IOException e) {
	}

	return properties;
    }

    /**
     * Stores values in the properties file. Uses the existing file.
     * 
     * @param path path to store
     * @param ip ip to store
     * @param port port to store
     */
    public static void storeProperties(String path, String ip, String port) {
	Properties properties = readProperties();
	
	if (path != null) {
	    properties.setProperty(PROP_PATH, checkParameter(path));
	}
	if (ip != null) {
	    properties.setProperty(PROP_IP, checkParameter(ip));
	} else {
	    
	}
	if (port != null) {
	    properties.setProperty(PROP_PORT, checkParameter(port));
	}
	// Write properties file.
	try {
	    properties.store(new FileOutputStream("suncertify.properties"),
		    null);
	} catch (IOException e) {
	    GuiExceptionHandler
		    .handleGuiException("Error writing properties. Please restart application.");
	}
    }

    /**
     * Checks if a parameter is empty.
     * 
     * @param parameter
     * @return the parameter or an empty string, if the parameter is empty.
     */
    private static String checkParameter(String parameter) {
	if (StringUtils.isEmpty(parameter)) {
	    return "";
	}

	return parameter;
    }
}
